/*
 * @Discription: 
 * @Company: 512354087@qq.com
 * @Author: Donie
 * @LastEditors: OBKoro1
 * @Date: 2019-05-10 15:03:28
 * @LastEditTime: 2019-05-10 15:36:43
 */

var Api = require('../utils/api.js');
var util = require('../utils/util.js');
var bdApi = require('../utils/bdApi.js')
var bdRequest = require('../utils/bdRequest.js')
var app = getApp();
const Auth = {}

Auth.checkSession = function(appPage, flag) {
  let openid = swan.getStorageSync('openid');
  if (!openid) {
    if ('isLoginNow' == flag) {
      var userInfo = {
        avatarUrl: "https://www.bds110.com/wp-content/uploads/bdsmp-dacx/gravatar.png",
        nickName: "登录",
        isLogin: false
      }
      appPage.setData({
        isLoginPopup: true,
        userInfo: userInfo
      });
    }

  }
}
Auth.checkLogin = function(appPage) {
  let swanLoginInfo = swan.getStorageSync('swanLoginInfo');
  swan.checkSession({
    success: function() {
      if (!swanLoginInfo.js_code) {
        Auth.swanLogin().then(res => {
           console.log('登录态有效',res);
            swan.getUserInfo({
                success: function (res) {
                    console.log('用户名', res);
                    swan.setStorageSync('userInfo',res)
                }
            })
            appPage.setData({
                swanLoginInfo: res
            });
            swan.setStorageSync('swanLoginInfo', res);
        })
      }
    },
    fail: function() {
      Auth.swanLogin().then(res => {
        appPage.setData({
          swanLoginInfo: res
        });
           console.log('登录态有效',res);
            swan.getUserInfo({
                success: function (res) {
                    console.log('用户名', res.userInfo); 
                }
            })
       swan.setStorageSync('swanLoginInfo', res);
      })
    }
  })
}
Auth.checkAgreeGetUser = function(e, app, appPage, authFlag) {
  let swanLoginInfo = swan.getStorageSync('swanLoginInfo');
  console.log(swanLoginInfo,111111111111133333333333)
  if (swanLoginInfo.js_code) {
    Auth.agreeGetUser(e, swanLoginInfo, authFlag).then(res => {
      console.log(res,11111111222)
      if (res.errcode == "") {
        swan.setStorageSync('userInfo', res.userInfo);
        console.log(res,11111111)
        swan.setStorageSync('openid', res.openid);
        appPage.setData({
          openid: res.openid
        });
        appPage.setData({
          userInfo: res.userInfo
        });

      } else {
        var userInfo = {
          avatarUrl: "https://www.bds110.com/wp-content/uploads/bdsmp-dacx/gravatar.png",
          nickName: "点击登录",
          isLogin: false
        }
        appPage.setData({
          userInfo: userInfo
        });
        console.log("用户拒绝了授权");
      }
      appPage.setData({
        isLoginPopup: false
      });

    })
  } else {
    console.log("登录失败");
    swan.showToast({
      title: '登录失败',
      mask: false,
      duration: 1000
    });

  }
}

Auth.agreeGetUser = function(e, swanLoginInfo, authFlag) {
console.log(12345)
  return new Promise(function(resolve, reject) {
    let args = {};
    let data = {};
    args.js_code = swanLoginInfo.js_code;
    if (authFlag == '0' && e.detail.errMsg == 'getUserInfo:fail auth deny') {
      args.errcode = e.detail.errMsg;
      args.userInfo = {
        isLogin: false
      }
      args.userSession = "";
      resolve(args);
      return;
    }
    var userInfoDetail = {};
    if (authFlag == '0') //未授权过,通过按钮授权
    {
      userInfoDetail = e.detail;
    } else if (authFlag == '1') //已经授权过，直接通过swan.getUserInfo获取
    {
      userInfoDetail = e;
    }
    if (userInfoDetail && userInfoDetail.userInfo) {
      args.iv = userInfoDetail.iv;
      args.encryptedData = userInfoDetail.encryptedData;
      let userInfo = userInfoDetail.userInfo;
      userInfo.isLogin = true;
      args.avatarUrl = userInfo.avatarUrl;
      args.nickname = userInfo.nickName;
      data.userInfo = userInfo;
      var url = Api.getOpenidUrl();
      var postOpenidRequest = bdRequest.postRequest(url, args);
      //获取openid
      postOpenidRequest.then(response => {
        if (response.data.status == '200') {
          //console.log(response.data.openid)
          console.log("授权登录获取成功");
          data.openid = response.data.openid;
          data.errcode = "";
          resolve(data);

        } else {
          console.log(response);
          reject(response);
        }
      }).catch(function(error) {
        console.log('error: ' + error);
        reject(error);
      })

      // Auth.userLogin(args,api).then(userSession=>{
      //     args.userSession=userSession;
      //     args.errcode ="";
      //     resolve(args);
      // }).catch(function (error) {
      //     console.log('error: ' + error);                        
      //     reject(error);
      // })
    } else {
      args.errcode = "error";
      args.userInfo = {
        isLogin: false
      };
      args.userSession = "";
      resolve(args);
    }
  })
}
Auth.setUserInfoData = function(appPage) {
  if (!appPage.data.openid) {
    appPage.setData({
      userInfo: swan.getStorageSync('userInfo'),
      openid: swan.getStorageSync('openid')
    })

  }

}
Auth.swanLogin = function() {
  return new Promise(function(resolve, reject) {
    swan.login({
      success: function(res) {
        console.log(res)
        let args = {};
        args.js_code = res.code;
        resolve(args);
      },
      fail: function(err) {
        console.log(err);
        reject(err);
      }
    });
  })

}

Auth.logout = function() {
  // this.setData({
  //   openid: {},
  //   userInfo: {},
  // })
  swan.removeStorageSync('swanLoginInfo');
  swan.removeStorageSync('logs');
  swan.removeStorageSync('userInfo');
  swan.removeStorageSync('openid');
  swan.removeStorageSync('openLinkCount');
  swan.removeStorageSync('readLogs');
}

module.exports = Auth;